<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Java-函数式接口 |  Yolin
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.png" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="Yolin" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Java-函数式接口" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Java-函数式接口
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/08/28/Java-%E5%87%BD%E6%95%B0%E5%BC%8F%E6%8E%A5%E5%8F%A3/" class="article-date">
  <time datetime="2020-08-28T09:58:02.000Z" itemprop="datePublished">2020-08-28</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.1k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">4分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h2 id="1-1-函数式接口概述"><a href="#1-1-函数式接口概述" class="headerlink" title="1.1 函数式接口概述"></a>1.1 函数式接口概述</h2><p><strong>函数式接口：有且仅有一个抽象方法的接口</strong></p>
<p>Java中的函数式编程体现就是Lambda表达式，所以函数式接口就是可以适用于Lambda使用的接口，只有确保接口中有且仅有一个抽象方法，Java中的Lambda才能顺利进行推导</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_10-56-58.jpg" alt=""></p>
<p>检测一个接口是否为函数式接口用 <strong>@FunctionalInterface</strong>，放在接口定义上方如果是编译通过，反之。</p>
<a id="more"></a>
<p>注意：定义函数式接口时，@FunctionalInterface是可选的，不写注解需满足函数式接口的定义条件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@FunctionalInterface</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">MyInterface</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">show</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-2-函数式接口作为方法的参数"><a href="#1-2-函数式接口作为方法的参数" class="headerlink" title="1.2 函数式接口作为方法的参数"></a>1.2 函数式接口作为方法的参数</h2><p>需求：</p>
<ul>
<li>定义一个类(RunnableDemo),提供两个方法</li>
</ul>
<blockquote>
<p>一个是startThread(Runnable r) 方法参数Runnable是一个函数式接口</p>
<p>一个是主方法，在主方法中调用startThread方法</p>
</blockquote>
<p>将Lambda表达式作为参数传递<br><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_11-21-26.jpg" alt=""></p>
<p><strong>如果方法的参数是一个函数式接口，我们可以使用Lambda表达式作为参数传递</strong></p>
<h2 id="1-3-函数式接口作为方法的返回值"><a href="#1-3-函数式接口作为方法的返回值" class="headerlink" title="1.3 函数式接口作为方法的返回值"></a>1.3 函数式接口作为方法的返回值</h2><p>需求：</p>
<ul>
<li>定义一个类（ComparatorDemo)，在类中提供两个方法</li>
</ul>
<blockquote>
<p>一个是：Comparator<String> getComparator() 方法返回值Comparator是一个函数式接口</p>
<p>一个是主方法，在主方法中调用getCompartor方法</p>
</blockquote>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_12-18-01.jpg" alt=""></p>
<p><strong>如果方法的返回值是一个函数式接口，我们可以使用Lambda表达式作为结果返回</strong></p>
<p>改造后：<br><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_12-31-57.jpg" alt=""></p>
<h2 id="1-4-常用的函数式接口"><a href="#1-4-常用的函数式接口" class="headerlink" title="1.4 常用的函数式接口"></a>1.4 常用的函数式接口</h2><p>Java8在java.util.function包下预定了大量的函数式接口供我们使用</p>
<p>常用的有：</p>
<ul>
<li>Supplier接口</li>
<li>Consumer接口</li>
<li>Predicate接口</li>
<li>Function接口</li>
</ul>
<h2 id="1-5-Supplier接口"><a href="#1-5-Supplier接口" class="headerlink" title="1.5 Supplier接口"></a>1.5 Supplier接口</h2><p>Supplier<T>: 包含一个无参的方法</p>
<ul>
<li>T get(): 获得结果</li>
<li>该方法不需要参数，它会按照某种逻辑(由Lambda表达式实现)返回一个数据</li>
<li>Supplier<T>接口也被称为生产型接口，如果我们制定了接口的泛型是什么类型，那么接口中的get方法就会产生什么类型的数据供我们使用</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_18-12-53.jpg" alt=""></p>
<h3 id="练习"><a href="#练习" class="headerlink" title="练习"></a>练习</h3><ul>
<li>定义一个类(Supplier Test),在类中提供两个方法</li>
</ul>
<blockquote>
<p>一个方法是：int getMax(Supplier<Integer> sup)用于返回一个int数组中的最大值</p>
<p>主方法调用getMax方法</p>
</blockquote>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_18-32-46.jpg" alt=""></p>
<h2 id="1-6-Consumer接口"><a href="#1-6-Consumer接口" class="headerlink" title="1.6 Consumer接口"></a>1.6 Consumer接口</h2><p>Consumer<T>:包含两个方法</p>
<ul>
<li>void accept(T t):对给定的参数执行此操作</li>
<li>default Consumer<T> andThen(Consumer after):返回一个组合的Consumer,依次执行此操作，然后执行after操作</li>
<li>Consumer<T>接口也被称为消费型接口，它消费的数据的数据类型由泛型决定</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_20-31-43.jpg" alt=""></p>
<h3 id="练习-1"><a href="#练习-1" class="headerlink" title="练习"></a>练习</h3><ul>
<li>定义字符串数组</li>
</ul>
<blockquote>
<p>String[] strArray={“猪头鑫,22”,”刘升升，23”,”张欢欢，24”};</p>
</blockquote>
<ul>
<li>字符串数组中有多条信息，请按照格式：“姓名：xx，年龄：xx”的格式将信息打印出来</li>
<li>要求：</li>
</ul>
<blockquote>
<p>把打印姓名的动作作为第一个Consumer接口的Lambda实例</p>
<p>把打印年龄的动作作为第二个Consumer接口的Lambda实例</p>
<p>将两个Consumer接口按照顺序组合到一起使用</p>
</blockquote>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-27_22-16-37.jpg" alt=""></p>
<h2 id="1-7-Predicate接口"><a href="#1-7-Predicate接口" class="headerlink" title="1.7 Predicate接口"></a>1.7 Predicate接口</h2><p>Predicate<T>:常用的四个方法</p>
<ul>
<li>boolean test(T t):对给定的参数进行判断(判断逻辑由Lambda表达式实现)，返回一个布尔值</li>
<li>default Predicate<T> negate():返回一个逻辑的否定，对应<strong>逻辑非</strong></li>
<li>default Predicate<T> and(Predicate other):返回一个组合判断，对应<strong>短路与</strong></li>
<li>default Predicate<T> or(Predicate other):返回一个组合判断，对应<strong>短路或</strong></li>
<li>Predicate<T><strong>接口通常用于判断参数是否满足指定的条件</strong></li>
</ul>
<h3 id="test方法"><a href="#test方法" class="headerlink" title="test方法"></a>test方法</h3><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-28_09-14-12.jpg" alt=""></p>
<h3 id="negate方法"><a href="#negate方法" class="headerlink" title="negate方法"></a>negate方法</h3><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-28_09-17-30.jpg" alt=""></p>
<h3 id="and和or方法"><a href="#and和or方法" class="headerlink" title="and和or方法"></a>and和or方法</h3><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-28_10-24-36.jpg" alt=""></p>
<h3 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h3><ul>
<li>String[] strArray={“刘生生,28”,”朱同心,65”,”王凡,36”,”张虎强,35”,”胡智升,36”};</li>
<li>字符串数组中有多条信息，请通过Predicate接口的拼装将符合要求的字符串筛选到集合ArrayList中，并遍历ArrayList集合</li>
<li>同时满足如下需求：姓名长度大于2，年龄大于33</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-28_11-29-00.jpg" alt=""></p>
<h2 id="1-8-Function接口"><a href="#1-8-Function接口" class="headerlink" title="1.8 Function接口"></a>1.8 Function接口</h2><p>Function&lt;T,R&gt;:常用的两个方法</p>
<ul>
<li>R apply(T t):将此函数应用于给定的参数</li>
<li>default<V> Function andThen(Function after):返回一个组合函数，首先将该函数应用于输入，然后将after函数应用于结果</li>
<li>Function&lt;T,R&gt;接口<strong>通常用于对参数进行处理，转换(处理逻辑由Lambda表达式实现)，然后返回一个新的值</strong></li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-28_17-20-22.jpg" alt=""></p>
<h3 id="案例-1"><a href="#案例-1" class="headerlink" title="案例"></a>案例</h3><ul>
<li>String s=”猪头新,33”;</li>
<li>按指定要求操作：</li>
</ul>
<blockquote>
<p>1.将字符串截取到数字部分</p>
<p>2.将数字转换为int类型数据</p>
<p>3.将数据减10，得到一个int结果，输出在控制台</p>
</blockquote>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-28_17-53-43.jpg" alt=""></p>

      
      <!-- reward -->
      
    </div>
      <!-- copyright -->
      
    <footer class="article-footer">
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F%E6%8E%A5%E5%8F%A3/" rel="tag">函数式接口</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/08/30/Java-Stream%E6%B5%81/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Java-Stream流
          
        </div>
      </a>
    
    
      <a href="/2020/08/25/Java-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Java-方法引用</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020-2021
        张金
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
        <img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/beian.png">
        <a href="https://beian.miit.gov.cn"  style="color:#f72b07" target="_blank">陕ICP备20002449号</a>
      </li>

    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Yolin"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/playlist">歌单</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/video">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友情链接</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['肠断月明红豆蔻,','月似当时,','人似当时否？'],
    startDelay: 1500,
    typeSpeed: 200,
    loop: true,
    backSpeed: 40,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>